package org.elephas.webapp.backend.component.management;

import java.io.Serializable;
import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.elephas.model.BlogMembership;
import org.elephas.persistence.query.QueryParam;
import org.elephas.persistence.query.Sort;
import org.elephas.service.UserFinder;
import org.elephas.webapp.model.DetachableBlogMembershipModel;
import org.elephas.webapp.model.DetachableBlogModel;

import salve.depend.Dependency;

/**
 * @author Gerolf Seitz
 * 
 */
public class SortableBlogMembershipDataProvider extends SortableDataProvider {
	private static final long serialVersionUID = 1L;

	@Dependency
	private UserFinder finder;

	private final DetachableBlogModel blogModel;

	public SortableBlogMembershipDataProvider(DetachableBlogModel blogModel) {
		this.blogModel = blogModel;
		setSort("user.emailAddress", true);
	}

	public Iterator<BlogMembership> iterator(int first, int count) {
		QueryParam param = new QueryParam(first, count, newSort(getSort()));
		if (blogModel != null) {
			return blogModel.getObject().getMemberships(param).iterator();
		}
		return finder.findMemberships(param).iterator();
	}

	public IModel model(Object object) {
		return new DetachableBlogMembershipModel((BlogMembership) object);
	}

	public int size() {
		if (blogModel != null) {
			return blogModel.getObject().countMemberships();
		}
		return finder.countMemberships();
	}

	public void detach() {

	}

	private Sort[] newSort(final SortParam sort) {
		return new Sort[] { new Sort() {

			public Serializable getData() {
				return sort.getProperty();
			}

			public boolean isAscending() {
				return sort.isAscending();
			}

		} };
	}
}
